package com.itboye.textileexpres.top;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.R.integer;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

import com.alipay.a.a.c;
import com.itboye.textileexpes.beans.GoodsDetailBean;
import com.itboye.textileexpes.presenter.GoodsPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.alipaytest.ActivityPaymentMethod;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.main.MainActivity;
import com.itboye.textileexpres.myset.ActivityCustomerDetail;
import com.itboye.textileexpres.top.GoodsDetailsActivity.JiaRuGouWuCheDialog;
import com.itboye.textileexpres.util.BaseDialogFragment;
import com.itboye.textileexpres.util.MyToast;
import com.itboye.textileexpres.util.TimeFormat;
import com.itboye.textileexpres.util.XImageLoader;
import com.itboye.textileexpres.widget.CarouselView;
import com.itboye.textileexpres.widget.DertailServiceDialog;
import com.itboye.textileexpres.widget.RoundImageView;
import com.itboye.textileexptes.config.GlobalConfig;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.Animator.AnimatorListener;

public class GoodsDetail extends BaseActivity implements Observer,
		OnClickListener {
	ImageView back;
	TextView title;
	ImageView img_other;
	ImageView img_search;
	PopupWindow popupWindow;
	TextView share_tv, new_tv, main_tv;
	LinearLayout shopcart_lin, buy_lin;
	CarouselView topLunbo;
	private List<ImageView> bmps;
	TextView publish_time, Publish_people_name, collect_num, goods_num,
			goods_name, goods_detail, price_1_tv, limit_1, price_2_tv, limit_2,
			price_3_tv, limit_3, address_tv, color_tv, type_tv, service_tv,
			choose_tv;
	TextView product_attr, pinpai_tv, huohao_tv, caizhi_tv;
	LinearLayout sercice_lin;
	RoundImageView person_img;
	TextView name, phone;
	String pid;
	RelativeLayout top_rel;
	GoodsPresenter presenter;
	GoodsDetailBean detailBean;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_goodsdetail;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		title.setText("商品详情");
		pid = getIntent().getStringExtra("pid");
		presenter = new GoodsPresenter(this);
		presenter.DetailQuery("40");
		Log.e("hu.detaile", pid + "");
		img_search.setImageResource(R.drawable.goods_shopcart);
		img_other.setImageResource(R.drawable.goods_more);
		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				View popView = LayoutInflater.from(GoodsDetail.this).inflate(
						R.layout.pop_goods_detail, null);
				share_tv = (TextView) popView.findViewById(R.id.share_tv);
				new_tv = (TextView) popView.findViewById(R.id.news_tv);
				main_tv = (TextView) popView.findViewById(R.id.main_tv);
				share_tv.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						// Toast(GoodsDetailsActivity.this, "share");
						popupWindow.dismiss();
					}
				});
				new_tv.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						toast("new");
						popupWindow.dismiss();
					}
				});
				main_tv.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(GoodsDetail.this,
								MainActivity.class);
						startActivity(intent);
						popupWindow.dismiss();
					}
				});
				popupWindow = new PopupWindow(popView, ChangeToDP(100),
						LayoutParams.WRAP_CONTENT);
				popupWindow.setOutsideTouchable(true);
				popupWindow.setBackgroundDrawable(new BitmapDrawable());
				popupWindow.showAsDropDown(v);

			}
		});
		shopcart_lin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new JiaRuGouWuCheDialog().show(getSupportFragmentManager(), "");
			}
		});
		color_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new JiaRuGouWuCheDialog().show(getSupportFragmentManager(), "");
			}
		});
		service_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DertailServiceDialog(GoodsDetail.this).show(
						getSupportFragmentManager(), "");
			}
		});
		// onBaner();
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == GoodsPresenter.Detail_success) {
				detailBean = (GoodsDetailBean) entity.getData();
				onBaner();
			} else if (entity.getEventType() == GoodsPresenter.Detail_fail) {
				MyToast.toast("" + entity.getData());
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.back:

			finish();
			break;
		case R.id.buy_lin:
			intent = new Intent(GoodsDetail.this, ActivityPaymentMethod.class);
			startActivity(intent);
			break;
		case R.id.img_search:
			intent = new Intent(GoodsDetail.this, ActivityCustomerDetail.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void onBaner() {
		// TODO Auto-generated method stub
		publish_time
				.setText(TimeFormat.DateFormat(detailBean.getExpire_time()));
		Publish_people_name.setText(":" + detailBean.getContact_name() + "");
		name.setText("" + detailBean.getContact_name() + "");
		collect_num.setText(detailBean.getFavorite_cnt() + "");
		goods_num.setText("产品编号:" + detailBean.getProduct_code() + "");
		goods_name.setText(detailBean.getName() + "");
		goods_detail.setText(detailBean.getSynopsis() + "");
		pinpai_tv.setText(detailBean.getName() + "");
		huohao_tv.setText(detailBean.getProduct_code() + "");
		caizhi_tv.setText(detailBean.getProduct_code() + "");
		phone.setText("联系方式：" + detailBean.getContact_way());
		if ("".equals(detailBean.getSku_list().get(1).getPrice())) {
			price_2_tv.setVisibility(View.GONE);
			limit_2.setVisibility(View.GONE);
		} else if ("".equals(detailBean.getSku_list().get(2).getPrice())) {
			price_3_tv.setVisibility(View.GONE);
			limit_3.setVisibility(View.GONE);
		}
		price_1_tv.setText("￥" + detailBean.getSku_list().get(0).getPrice());
		price_2_tv.setText("￥" + detailBean.getSku_list().get(0).getPrice2());
		price_3_tv.setText("￥" + detailBean.getSku_list().get(0).getPrice3());
		limit_1.setText("" + detailBean.getSku_list().get(0).getCnt1() + "条起批");
		limit_2.setText("" + detailBean.getSku_list().get(0).getCnt2() + "-"
				+ detailBean.getSku_list().get(0).getCnt3());
		limit_3.setText(">" + detailBean.getSku_list().get(0).getCnt3() + "");
		address_tv.setText(detailBean.getPlace_origin() + "");
		StringBuffer color = new StringBuffer();
		// StringBuffer type = new StringBuffer();
		for (int i = 0; i < detailBean.getSku_list().size(); i++) {
			String desc = new String();
			desc = (detailBean.getSku_list().get(i).getSku_desc());
			// color.append(desc.substring(desc.indexOf("颜色") + 3,
			// desc.indexOf("尺码")));
			// type.append(desc.subSequence(desc.indexOf("尺码") + 3,
			// desc.length()));
			color.append(detailBean.getSku_list().get(i).getSku_desc());
			// type.append(desc.subSequence(desc.indexOf("尺码") + 3,
			// desc.length()));

		}
		// color_tv.setText(detailBean.getSku_list().get(0).getSku_desc());
		color_tv.setText("" + color + "");
		// type_tv.setText("规格：" + type);
		topLunbo = (CarouselView) findViewById(R.id.topLunbo);
		bmps = new ArrayList<ImageView>();
		for (int i = 0; i < detailBean.getCarousel_images().size(); i++) {
			ImageView imageView = new ImageView(this);
			imageView.setScaleType(ScaleType.FIT_XY);

			com.nostra13.universalimageloader.core.ImageLoader.getInstance()
					.displayImage(
							GlobalConfig.IMAGE_DOUBLE
									+ detailBean.getCarousel_images().get(i),
							imageView);
			bmps.add(imageView);

		}
		topLunbo.setImageBitmaps(bmps);
	}

	class JiaRuGouWuCheDialog extends BaseDialogFragment {
		View close;
		ImageView pic;
		TextView unit;
		TextView total_price, total_num2;
		TextView price;
		TextView goods_number_tv;
		ViewGroup guigeContainer;
		View ok;
		View jian;
		View jia;
		EditText input;
		boolean isLiJIGouMai;
		ViewGroup container;
		String imgUrl;
		protected String priceString;
		protected String skuId;
		double total;
		int totalNum;
		ArrayList<EditText> hashMap = new ArrayList<EditText>();

		public JiaRuGouWuCheDialog() {

		}

		void DialogTopShow(int i) {
			price.setText(detailBean.getSku_list().get(i).getPrice());
			goods_number_tv.setText("产品编号："
					+ detailBean.getSku_list().get(i).getProduct_code());
			XImageLoader.load(GlobalConfig.IMAGE_DOUBLE
					+ detailBean.getSku_list().get(i).getSku_pkid(), pic);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			return LayoutInflater.from(GoodsDetail.this).inflate(
					R.layout.dialog_add_shopcart, null);
		}

		private TextView createTitle(String s) {
			TextView textView = new TextView(GoodsDetail.this);
			textView.setText(s);
			textView.setTextColor(Color.BLACK);
			return textView;
		}

		public void close() {
			View v = getView().findViewById(R.id.container);
			ObjectAnimator animator = ObjectAnimator.ofFloat(v, "translationY",
					0, v.getHeight()).setDuration(300);
			animator.addListener(new AnimatorListener() {
				@Override
				public void onAnimationStart(Animator arg0) {
				}

				@Override
				public void onAnimationRepeat(Animator arg0) {
				}

				@Override
				public void onAnimationEnd(Animator arg0) {
					dismiss();
				}

				@Override
				public void onAnimationCancel(Animator arg0) {
					dismiss();
				}
			});
			animator.start();
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {

			super.onActivityCreated(savedInstanceState);

			if (savedInstanceState != null) {
				// goodsDetailBeans = (GoodsDetailsRootBean) savedInstanceState
				// .getSerializable("goodsDetailBeans");
				// isLiJIGouMai = savedInstanceState.getBoolean("isLiJIGouMai");
			}
			XImageLoader.load(GlobalConfig.IMAGE_DOUBLE
					+ detailBean.getSku_list().get(0).getSku_pkid(), pic);
			price.setText(detailBean.getSku_list().get(0).getPrice());
			unit.setText(detailBean.getGoods_unit_name());
			goods_number_tv.setText("产品编号："
					+ detailBean.getSku_list().get(0).getProduct_code());
			for (int i = 0; i < detailBean.getSku_list().size(); i++) {
				View view = LayoutInflater.from(GoodsDetail.this).inflate(
						R.layout.item_detail_goods, null);
				TextView color_tv = (TextView) view.findViewById(R.id.color_tv);
				TextView price_m = (TextView) view.findViewById(R.id.price_m);
				TextView kucun = (TextView) view.findViewById(R.id.kucun);
				TextView jian = (TextView) view.findViewById(R.id.jian);
				TextView jia = (TextView) view.findViewById(R.id.jia);
				final EditText input = (EditText) view.findViewById(R.id.input);
				price_m.setText("￥"
						+ detailBean.getSku_list().get(i).getPrice() + "");
				kucun.setText("库存"
						+ detailBean.getSku_list().get(i).getQuantity() + "");
				color_tv.setText(detailBean.getSku_list().get(i).getSku_desc()
						+ "");
				jian.setTag(i);
				jia.setTag(i);
				hashMap.add(input);
				jian.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						DialogTopShow((int) v.getTag());

						String s = input.getText().toString();
						try {
							int c = Integer.parseInt(s);
							if (c > 0) {
								c--;
							}
							input.setText(c + "");
						} catch (NumberFormatException e) {
							input.setText("1");
						}
						input.setSelection(input.getText().length());
						// total = Integer.parseInt(detailBean.getSku_list()
						// .get((int) v.getTag()).getPrice())
						// * Integer.parseInt(input.getText() + "");
						// total_price.setText(total + "");
						total = 0;
						totalNum = 0;
						for (int j = 0; j < hashMap.size(); j++) {
							total += Double.parseDouble(detailBean
									.getSku_list().get(j).getPrice())
									* Integer.parseInt(hashMap.get(j).getText()
											+ "");
							totalNum += Integer.parseInt(hashMap.get(j)
									.getText() + "");
						}
						total_price.setText(total + "");
						total_num2.setText("" + totalNum);
					}

				});
				jia.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						DialogTopShow((int) v.getTag());
						String s = input.getText().toString();
						try {
							int c = Integer.parseInt(s);
							input.setText(c + 1 + "");
						} catch (NumberFormatException e) {
							input.setText("1");
						}
						input.setSelection(input.getText().length());
						// total += Integer.parseInt(detailBean.getSku_list()
						// .get((int) v.getTag()).getPrice())
						// * Integer.parseInt(input.getText() + "");

						total = 0;
						totalNum = 0;
						for (int j = 0; j < hashMap.size(); j++) {
							total += Double.parseDouble(detailBean
									.getSku_list().get(j).getPrice())
									* Integer.parseInt(hashMap.get(j).getText()
											+ "");
							totalNum += Integer.parseInt(hashMap.get(j)
									.getText() + "");
						}
						total_price.setText(total + "");
						total_num2.setText("" + totalNum);
					}
				});
				guigeContainer.addView(view);
			}

			// jia.setOnClickListener(new OnClickListener() {
			// @Override
			// public void onClick(View v) {
			// String s = input.getText().toString();
			// try {
			// int c = Integer.parseInt(s);
			// input.setText(c + 1 + "");
			// } catch (NumberFormatException e) {
			// input.setText("1");
			// }
			// input.setSelection(input.getText().length());
			// }
			// });
			// jian.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// String s = input.getText().toString();
			// try {
			// int c = Integer.parseInt(s);
			// if (c > 0) {
			// c--;
			// }
			// input.setText(c + "");
			// } catch (NumberFormatException e) {
			// input.setText("0");
			// }
			// input.setSelection(input.getText().length());
			// }
			// });
			close.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					close();
				}
			});
			ok.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dismiss();
				}
			});

		}
	}
}
